//
//  ManagerViewController.m
//  NewBook
//
//  Created by dlios on 15-3-7.
//  Copyright (c) 2015年 dlios. All rights reserved.
//

#import "ManagerViewController.h"

@interface ManagerViewController ()

@end

@implementation ManagerViewController

-(void)dealloc
{
    [_myTableView release];
    [_allYoungArray release];

    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化数组
    self.dataArray = [[NSMutableArray alloc]init];

    self.allYoungArray = [NSMutableArray array];
    
    self.view.frame = CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height - 60);
    
    
    //创建tableView,用来显示
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 60 - 10) style:UITableViewStylePlain];
    //把tableView的分割线去掉
        self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.myTableView.delegate = self;
        self.myTableView.dataSource = self;
        [self.view addSubview:self.myTableView];
        [_myTableView release];
    
    __block ManagerViewController *root = self;
    
    NSString *urlStr = @"http://mapi.dangdang.com/index.php?action=list_category&user_client=iphone&client_version=5.0.1&page=2&page_size=10&sort_type=default_0&cid=01.22.00.00.00.00&img_size=h&udid=18948B21919333DDC1DDE273A67E5005&time_code=5B34F255711B3EB9DCF6E879382942F9&timestamp=1425629582&union_id=537-50&permanent_id=20150304193014100686115327268485015";
    
    
    //AFN请求数据
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", nil];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableDictionary *youngDic = responseObject;
        
        NSMutableArray *youngArray = [youngDic objectForKey:@"products"];
        
        for (NSMutableDictionary *dic in youngArray) {
            
            YoungBook *youngBook = [[YoungBook alloc] init];
            [youngBook setValuesForKeysWithDictionary:dic];
            youngBook.productId = [dic objectForKey:@"id"];
            [root.allYoungArray addObject:youngBook];
            
            [youngBook release];
        }
        
        [self.myTableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败 == %@", error);
    }];

    
    [self addHeader];
    [self addFooter];
}

//下拉刷新
- (void)addHeader
{
    //NSLog(@"下拉刷新");
    __block ManagerViewController *movieVC = self;
    [self.myTableView addHeaderWithCallback:^{
        //NSLog(@"222");
        movieVC.isUpLoading = NO;
        [self GetMovieList:0];
    }];
    [self.myTableView headerBeginRefreshing];
}
//上拉加载
- (void)addFooter
{
    //NSLog(@"上拉刷新");
    __block ManagerViewController *movieVC = self;
    [self.myTableView addFooterWithCallback:^{
        //NSLog(@"333");
        movieVC.isUpLoading = YES;
        [movieVC GetMovieList:movieVC.page];
        
    }];
}

//AFN请求数据
- (void)GetMovieList:(NSInteger)page
{
    
    __block ManagerViewController *root = self;
    
    NSString *url_string = [NSString stringWithFormat:@"http://mapi.dangdang.com/index.php?action=list_category&user_client=iphone&client_version=5.0.1&page=%ld&page_size=10&sort_type=default_0&cid=01.22.00.00.00.00&img_size=h&udid=18948B21919333DDC1DDE273A67E5005&time_code=5B34F255711B3EB9DCF6E879382942F9&timestamp=1425629582&union_id=537-50&permanent_id=20150304193014100686115327268485015",page + 1];
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    //****参数count 的值: 是指定一页显示多少条数据
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableDictionary *youngDic = responseObject;
        //记录下一页
        //先取出saleDic字典下的page字典
        NSMutableDictionary *pageDic = [youngDic objectForKey:@"page"];
        //然后取出pageDic字典下对应的pageindex内容
        self.page = [[pageDic objectForKey:@"pageindex"] integerValue];
        
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.allYoungArray removeAllObjects];
        }
        
        NSMutableArray *youngArray = [youngDic objectForKey:@"products"];
        
        for (NSMutableDictionary *dic in youngArray) {
            
            YoungBook *youngBook = [[YoungBook alloc] init];
            [youngBook setValuesForKeysWithDictionary:dic];
            youngBook.productId = [dic objectForKey:@"id"];
            [root.allYoungArray addObject:youngBook];
            
            [youngBook release];
        }
        //创建字典,设置默认的点击事件是关闭的
        NSDictionary *dic = @{@"Cell": @"MainCell",@"isAttached":@(NO)};
        //循环,
        for (int i = 0 ; i<root.allYoungArray.count; i++) {
            [self.dataArray addObject:dic];
        }
        

        [self.myTableView footerEndRefreshing];//结束底部刷新效果
        [self.myTableView headerEndRefreshing];//结束头部刷新效果
        [self.myTableView reloadData];//刷新tableview
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}

//tableview返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
//tableview上cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"MainCell"])
    {
        static NSString *CellIdentifier = @"MainCell";
        ManagerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[ManagerTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        //将cell设置成点击时不变色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.youngBook = [self.allYoungArray objectAtIndex:indexPath.row];
        
        return cell;
    }
    else if([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"AttachedCell"]){
        
        static NSString *CellIdentifier = @"AttachedCell";
        
        AttachedManagerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        
        if (cell == nil) {
            cell = [[AttachedManagerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            
            //将button设为属性,点击按钮触发的方法
            [cell.detailButton addTarget:self action:@selector(detailButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell.collectionButton addTarget:self action:@selector(collectionButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        return cell;
        
    }
    return nil;
}

//点击cell跳转页面方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当点击大的cell时,把当前点击的大的cell上的对象取出来
    BookSale *bookSale = [self.allYoungArray objectAtIndex:indexPath.row];
    
    //创建AttachedYoungTableViewCell的对象
    self.attachedManagerCell = [[AttachedManagerTableViewCell alloc] init];
    //把当前的对象传给attachedYoungCell下的对象
    self.attachedManagerCell.bookSale = bookSale;
    
    //self.attachedYoungCell.indexx = indexPath.row;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    NSIndexPath *path = nil;
    
    if ([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"MainCell"]) {
        path = [NSIndexPath indexPathForItem:(indexPath.row+1) inSection:indexPath.section];
    }else{
        path = indexPath;
    }
    
    if ([[self.dataArray[indexPath.row] objectForKey:@"isAttached"] boolValue]) {
        // 关闭附加cell
        NSDictionary * dic = @{@"Cell": @"MainCell",@"isAttached":@(NO)};
        self.dataArray[(path.row-1)] = dic;
        [self.dataArray removeObjectAtIndex:path.row];
        
        [self.myTableView beginUpdates];
        [self.myTableView deleteRowsAtIndexPaths:@[path]  withRowAnimation:UITableViewRowAnimationMiddle];
        [self.myTableView endUpdates];
        
    }else{
        // 打开附加cell
        NSDictionary * dic = @{@"Cell": @"MainCell",@"isAttached":@(YES)};
        self.dataArray[(path.row-1)] = dic;
        NSDictionary * addDic = @{@"Cell": @"AttachedCell",@"isAttached":@(YES)};
        [self.dataArray insertObject:addDic atIndex:path.row];
        
        
        [self.myTableView beginUpdates];
        [self.myTableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationMiddle];
        [self.myTableView endUpdates];
        
    }

}
//设置tableview的cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断,如果是主cell,返回100
    if ([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"MainCell"])
    {
        return 100;
    }else{
        //否则返回40
        return 40;
    }
    return 0;
}


-(void)detailButtonAction:(UIButton *)button
{
    //创建bookDetailsVC的对象
    BookDetailsViewController *bookDetailsVC = [[BookDetailsViewController alloc]init];
    //将self.attachedYoungCell.bookSale对象下的属性分别赋值给详情页面的属性
    bookDetailsVC.title = self.attachedManagerCell.bookSale.name;
    bookDetailsVC.nameStr = self.attachedManagerCell.bookSale.name;
    bookDetailsVC.authornameStr = self.attachedManagerCell.bookSale.authorname;
    bookDetailsVC.subNameStr = self.attachedManagerCell.bookSale.subname;
    bookDetailsVC.priceStr = [NSString stringWithFormat:@"￥ :    %@",self.attachedManagerCell.bookSale.dd_sale_price];
    bookDetailsVC.detailsImageStr = self.attachedManagerCell.bookSale.image_url;
    bookDetailsVC.productId = self.attachedManagerCell.bookSale.productId;

    //跳到详情页面
    [self.navigationController pushViewController:bookDetailsVC animated:YES];
    [bookDetailsVC release];
}


//点击小的cell上的分享按钮触发的方法
- (void)shareButtonAction:(UIButton *)button
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren, UMShareToQzone, nil]
                                       delegate:self];
    
}
//点击小的cell上的收藏按钮触发的方法
- (void)collectionButtonAction:(UIButton *)button
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
